import dayjs from 'dayjs'
/**
 * 活动配置信息 主要用于配置活动中的activitySetting中的 基础设置和高级设置
 * tag 标签名称
 * component 组件名称(不必有，特殊需求使用)。分为通用和特殊组件，通用需配置tag，在tag基础上封装，特殊需配置component，直接使用。
 *          :目前已有通用组件【c-field-with-tip以及所有公共组件（机构、上传）】
 * usedTemplate 可使用该字段的模板 不配置或为空则表示所有模板都可以使用该字段
 * 全部模板信息 ['ACTE001','ACTE002','ACTE003','ACTE004','ACTE005','ACTE006','ACTE007','ACTE008','ACTE015','ACTE016','ACTE017','ACTE018','ACTE019','ACTE020','ACTE021','ACTE022','ACTE023','ACTE024','ACTE025','ACTE026','ACTE027','ACTE028','ACTE029']
 */
export const activityConfig = {
  activityBasicInfo: {
    basefield: [
      {
        tag: 'a-input',
        name: 'activityName',
        label: '活动名称',
        placeholder: '不能超过20个汉字',
      },
      {
        tag: 'a-radio-group',
        name: 'litePath',
        label: '游戏类型',
        options: [
          { label: '大转盘', value: '/pagesActivity/wheel/index' },
          { label: '刮刮乐', value: '/pagesActivity/scratchCard/index' },
          { label: '砸金蛋', value: '/pagesActivity/goldenEggs/goldenEggs' },
          { label: '翻翻乐', value: '/pagesActivity/flipMusic/flipMusic' },
        ],
        usedTemplate: ['ACTE001','ACTE008']
      },
      {
        tag: 'a-range-picker',
        name: 'activityTime',
        label: '活动时间',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        format: 'YYYY-MM-DD HH:mm:ss',
        showTime: { defaultValue: [dayjs().hour(0).minute(0).second(0), dayjs().hour(23).minute(59).second(59)] },
        disabledDate: (currentDate) => currentDate && currentDate < dayjs().endOf('day').subtract(1, 'day'),
        style: 'width: 100%',
      },
      {
        tag: 'a-textarea',
        component: 'c-field-with-tip',
        name: 'remark',
        label: '活动说明',
        placeholder: '请输入活动说明',
        rows: 4,
        tip: '回车换行'
      },
      {
        component: 'c-agent-select',
        name: 'agentNo',
        label: '机构',
      },
      {
        tag: 'a-select',
        name: 'wxOfficalAppId',
        label: '微信公众号',
        placeholder: '请选择微信公众号',
        options: [],  // 动态数据
        visibilityRules: [{ field: 'agentNo', operator: 'NOT_EMPTY' }]
      },
      {
        tag: 'a-select',
        name: 'wxMiniProgramAppId',
        label: '微信小程序',
        placeholder: '请选择微信小程序',
        options: [],  // 动态数据
        visibilityRules: [{ field: 'agentNo', operator: 'NOT_EMPTY' }]
      },
      {
        component: 'c-media-upload',
        name: 'imgUrl',
        label: '公众号素材图片',
        visibilityRules: [{ field: 'wxOfficalAppId', operator: 'NOT_EMPTY' }],
        // options: [],  // 动态数据
        // bizType: 'activity',
        // tip: '建议图片尺寸大小：520*416', // 兼容tip
      },
      {
        component: 'c-img-upload',
        name: 'activityImg',
        label: '活动图片',
        bizType: 'activity',
      },
      {
        tag: 'a-select',
        name: 'payAuthId',
        label: '出资方',
        placeholder: '请选择出资方',
        allowClear: true,
        options: [],  // 动态数据
      },
      {
        tag: 'a-checkbox-group',
        name: 'entryway',
        label: '流量入口',
        options: [
          { label: '小程序首页', value: '0' },
          { label: '机构展业工具入口', value: '1' },
          { label: '公众号渠道码', value: '2' },
          // { label: '广告', value: '3' },
          { label: '商家活动入口', value: '4' },
        ],
        usedTemplate: ['ACTE001', 'ACTE002', 'ACTE003', 'ACTE004', 'ACTE006', 'ACTE007', 'ACTE008', 'ACTE017', 'ACTE018', 'ACTE024', 'ACTE027', 'ACTE028', 'ACTE029']
      },
      {
        tag: 'a-input',
        name: 'litePath2',
        label: '小程序页面副路由',
        placeholder: '请输入小程序页面副路由',
        disabled: true,
        visibilityRules: {
          logic: 'AND',
          rules: [
            { field: 'entryway', operator: 'VALUE_IN', value: '0' },
            { field: 'entryway', operator: 'VALUE_IN', value: '2' },
          ]
        }
      },
      {
        component: 'c-img-upload',
        name: 'activityImg2',
        label: '活动副页面主图',
        bizType: 'activity',
        visibilityRules: {
          logic: 'AND',
          rules: [
            { field: 'entryway', operator: 'VALUE_IN', value: '0' },
            { field: 'entryway', operator: 'VALUE_IN', value: '2' },
          ]
        }
      }
    ]
  },
  // 模板 配置 对应关系
  activitySetting: {
    basefield: [
      {
        tag: 'a-radio-group',
        name: 'isFirstJoinScore',
        label: '首次参与福分奖励',
        options: [
          { label: '不奖励', value: 0 },
          { label: '首次参与奖励', value: 1 },
        ],
      },
      {
        tag: 'a-input-number',
        name: 'firstJoinScore',
        label: '首次参与奖励福分',
        min: 1,
        precision: 0,
        placeholder: '请输入奖励福分',
        visibilityRules: [{ field: 'isFirstJoinScore', value: 1 }],
      },
      {
        tag: 'a-radio-group',
        name: 'isEveryJoinScore',
        label: '每次参与福分奖励',
        options: [
          { label: '不奖励', value: 0 },
          { label: '每次参与福分奖励', value: 1 },
        ]
      },
      {
        tag: 'a-input-number',
        name: 'everyJoinScore',
        label: '每次参与奖励福分',
        min: 1,
        precision: 0,
        placeholder: '请输入奖励福分',
        visibilityRules: [{ field: 'isEveryJoinScore', value: 1 }],
      },
      {
        tag: 'a-radio-group',
        name: 'overType',
        label: '福分过期规则类型',
        options: [
          { label: 'n天后过期', value: 0 },
          { label: '指定过期时间', value: 1 },
          { label: '次季度首月月底失效', value: 2 },
        ],
        visibilityRules: {
          logic: 'OR',
          rules: [
            { field: 'isFirstJoinScore', value: 1 },
            { field: 'isEveryJoinScore', value: 1 },
          ],
        },
      },
      {
        tag: 'a-input-number',
        name: 'overDays',
        label: '过期天数',
        min: 1,
        precision: 0,
        placeholder: '请输入过期天数',
        visibilityRules: {
          logic: 'AND',
          rules: [
            {
              logic: 'OR',
              rules: [
                { field: 'isFirstJoinScore', value: 1 },
                { field: 'isEveryJoinScore', value: 1 },
              ],
            },
            { field: 'overType', value: 0 },
          ],
        },
      },
      {
        tag: 'a-date-picker',
        name: 'overTime',
        label: '过期时间',
        valueFormat: 'YYYY-MM-DD',
        disabledDate: (current) => current && current < dayjs().endOf('day'),
        style: 'width: 100%',
        visibilityRules: {
          logic: 'AND',
          rules: [
            {
              logic: 'OR',
              rules: [
                { field: 'isFirstJoinScore', value: 1 },
                { field: 'isEveryJoinScore', value: 1 },
              ],
            },
            { field: 'overType', value: 1 },
          ],
        },
      },{
        component: 'c-field-with-tip',
        tag: 'a-radio-group',
        name: 'awardType',
        label: '中奖概率设置',
        options: [
          { label: '按比例中奖', value: 0 },
          { label: '顺延中奖', value: 1 },
          { label: '百分百中奖', value: 2 }
        ],
        tip: '按比例中奖：按照实际设定的比例进行中奖，抽完特定等级的奖品后，后续抽中对应等级奖品的客户为空奖。\n顺延中奖：按照实际设定的比例进行中奖，抽完特定奖品后，顺延一个等级进行中奖，若所有的下级奖品抽完，才会出现空奖。\n百分百中奖：按照实际剩余的库存量设置实时中奖率，后台设置的中奖率无效化，直到奖品抽完才会出现空奖。'
      },{
        tag: 'a-radio-group',
        name: 'isOnlyOneTimes',
        label: '同一用户可参与次数限制',
        options: [
          { label: '不限制', value: 0 },
          { label: '限制', value: 1 },
        ]
      },{
        tag: 'a-input-number',
        name: 'onlyOneTimes',
        label: '同一用户可参与次数',
        min: 0,
        precision: 0,
        placeholder: '请输入同一用户可参与次数',
        visibilityRules: [{ field: 'isOnlyOneTimes', value: 1 }],
      },{
        tag: 'a-radio-group',
        name: 'periodType',
        label: '同一用户周期性限制参与限制',
        options: [
          { label: '不限制', value: 0 },
          { label: '限制每日', value: 1 },
          { label: '限制每周', value: 2 },
          { label: '限制每月', value: 3 },
        ]
      },{
        tag: 'a-input-number',
        name: 'periodTimes',
        label: '同一用户周期性限制参与限制次数',
        min: 0,
        precision: 0,
        placeholder: '请输入同一用户周期性限制参与限制次数',
        visibilityRules: [{ field: 'periodType', value: [1,2,3] }],
      },{
        tag: 'a-radio-group',
        name: 'specialType',
        label: '特殊参与限制',
        options: [
          { label: '不限制', value: 0 },
          { label: '每周几可以参与', value: 1 },
          { label: '特殊日期可以参与', value: 2 },
        ]
      },{
        tag: 'a-checkbox-group',
        name: 'specialContent',
        label: '每周几可以参与',
        options: [
          { label: '周一', value: '1' },
          { label: '周二', value: '2' },
          { label: '周三', value: '3' },
          { label: '周四', value: '4' },
          { label: '周五', value: '5' },
          { label: '周六', value: '6' },
          { label: '周日', value: '0' },
        ],
        visibilityRules: [{ field:'specialType', value: 1 }],
      },{
        component: 'c-special-date',
        tag: 'a-date-picker',
        name: 'specialContent',
        label: '特殊日期可以参与',
        visibilityRules: [{ field:'specialType', value: 2 }],
      },{
        tag: 'a-radio-group',
        name: 'timeType',
        label: '参与时间限制',
        options: [
          { label: '不限制', value: 0 },
          { label: '限制每个可参与的天', value: 1 },
        ]
      },{
        tag: 'a-time-range-picker',
        name: 'timeStartEnd',
        label: '限制每个可参与的天',
        format: 'HH:mm:ss',
        valueFormat: 'HH:mm:ss',
        visibilityRules: [{ field: 'timeType', value: 1 }]
      },{
        tag: 'a-radio-group',
        name: 'hasBlacklist',
        label: '是否开启黑名单',
        options: [
          { label: '不开启', value: 0 },
          { label: '开启', value: 1 }
        ]
      },{
        tag: 'a-checkbox-group',
        name: 'blacklistRuleIdList',
        label: '选择黑名单',
        options: [],
        visibilityRules: [{ field: 'hasBlacklist', value: 1 }],
      },{
        tag: 'a-radio-group',
        name: 'hasWhitelist',
        label: '是否开启白名单',
        options: [
          { label: '不开启', value: 0 },
          { label: '开启', value: 1 }
        ]
      },{
        tag: 'a-radio-group',
        name: 'thresholdType',
        label: '参与门槛限制',
        options: [
          { label: '不限制', value: 0 },
          { label: '限制', value: 1 },
        ]
      },{
        tag: 'a-input-number',
        name: 'thresholdFreeTimes',
        label: '前多少次免费',
        min: 0,
        precision: 0,
        placeholder: '请输入前多少次免费',
        visibilityRules: [{ field: 'thresholdType', value: 1 }],
      },{
        tag: 'a-input-number',
        name: 'thresholdJoinScore',
        label: '后续需消耗多少积分可参与',
        min: 0,
        precision: 0,
        placeholder: '请输入后续需消耗多少积分可参与',
        visibilityRules: [{ field: 'thresholdType', value: 1 }],
      },{
        tag: 'a-radio-group',
        name: 'isFollowOfficial',
        label: '参与活动是否需要关注公众号',
        options: [
          { label: '否', value: 0 },
          { label: '是', value: 1 }
        ]
      }
    ],
  },
  // 活动分享配置
  activityShare: {
    usedTemplate: ['ACTE008', 'ACTE024'], // 整个大类下使用的模板
    basefield: [
      {
        tag: 'a-textarea',
        name: 'shareText',
        label: '分享的文案',
        placeholder: '请输入分享的文案',
        rows: 4,
      },
      {
        component: 'c-img-upload',
        name: 'shareImgAppMessage',
        label: '转发给他人的图片链接',
        bizType: 'activity',
        accept: '.png,.jpg',
        tip: '推荐比例：5:4'
      },
      {
        component: 'c-img-upload',
        name: 'shareImgTimeline',
        label: '分享到朋友圈的图片链接',
        bizType: 'activity',
        accept: '.png,.jpg',
        tip: '推荐比例：1:1'
      },
      {
        tag: 'a-radio-group',
        name: 'shareSuccessStandard',
        label: '分享（单次）成功标准',
        options: [
          { label: '无要求', value: 0 },
          { label: '小程序新用户（注册手机号）', value: 1 },
          { label: '未参与过该活动的小程序用户', value: 2 },
          { label: '新实名用户', value: 3 },
        ]
      },
      {
        tag: 'a-radio-group',
        name: 'exchangeType',
        label: '奖品兑换类型',
        options: [
          { label: '单奖品兑换', value: 0 },
          { label: '多奖品中挑选一个兑换', value: 1 },
          { label: '积分兑换形式', value: 2 },
        ]
      },
      {
        tag: 'a-input-number',
        name:'shareMaxNum',
        label: '最大允许分享次数',
        min: 1,
        precision: 0,
        placeholder: '请输入最大允许分享次数',
      },
      {
        tag: 'a-input-number',
        name: 'toShareMaxNum',
        label: '被分享人最大允许助力次数',
        min: 1,
        precision: 0,
        placeholder: '请输入被分享人最大允许助力次数'
      },
      {
        tag: 'a-radio-group',
        name: 'sharePeriodType',
        label: '同一用户周期性分享次数限制类型',
        options: [
          { label: '不限制', value: 0 },
          { label: '限每日', value: 1 },
          { label: '限每周', value: 2 },
          { label: '限每月', value: 3 },
        ]
      },
      {
        tag: 'a-input-number',
        name: 'sharePeriodTimes',
        label: '同一用户周期性限制分享次数',
        min: 1,
        precision: 0,
        placeholder: '请输入同一用户周期性限制分享次数',
        visibilityRules: [{ field:'sharePeriodType', operator: 'NOT_EQUALS', value: 0 }],
      },
      {
        tag: 'a-radio-group',
        name: 'toSharePeriodType',
        label: '同一用户周期性助力次数限制类型',
        options: [
          { label: '不限制', value: 0 },
          { label: '限每日', value: 1 },
          { label: '限每周', value: 2 },
          { label: '限每月', value: 3 },
        ]
      },
      {
        tag: 'a-input-number',
        name: 'toSharePeriodTimes',
        label: '同一用户周期性限制助力次数',
        min: 1,
        precision: 0,
        placeholder: '请输入同一用户周期性限制助力次数',
        visibilityRules: [{ field:'toSharePeriodType', operator: 'NOT_EQUALS', value: 0 }],
      }
    ]
  }
}

/**
 * 检查字段值是否为空 (支持多类型)
 */
const isEmpty = (value) => {
  if (value === null || value === undefined) return true
  if (typeof value === 'string' && value.trim() === '') return true
  if (Array.isArray(value) && value.length === 0) return true
  if (typeof value === 'object' && Object.keys(value).length === 0) return true
  return false
}

/**
 * 增强版规则校验器
 */
const checkRule = (rule, formData) => {
  const fieldValue = formData[rule.field || rule.name] // 兼容 field/name
  // 1. 处理操作符优先
  if (rule.operator) {
    switch (rule.operator.toUpperCase()) {
      case 'NOT_EMPTY':
        return !isEmpty(fieldValue)
      case 'EMPTY':
        return isEmpty(fieldValue)
      case 'EQUALS':
        return fieldValue === rule.value
      case 'NOT_EQUALS':
        return fieldValue !== rule.value
      case 'IN':
        return Array.isArray(rule.value) && rule.value.includes(fieldValue)
      case 'NOT_IN':
        return Array.isArray(rule.value) && !rule.value.includes(fieldValue)
      case 'VALUE_IN':
        return Array.isArray(fieldValue) && fieldValue.includes(rule.value)
      case 'GT':
        return Number(fieldValue) > Number(rule.value)
      case 'LT':
        return Number(fieldValue) < Number(rule.value)
    }
  }
  // 2. 兼容旧版规则格式
  if (rule.range) {
    return fieldValue >= rule.range[0] && fieldValue <= rule.range[1]
  }
  if (Array.isArray(rule.value)) {
    return rule.value.includes(fieldValue)
  }
  if (rule.regex && typeof fieldValue === 'string') {
    return new RegExp(rule.regex).test(fieldValue)
  }
  // 3. 默认相等判断
  return fieldValue === rule.value
}

/**
 * 判断字段显示隐藏
 * @param {*} visibilityRules 配置项visibilityRules
 * @param {*} formData 表单数据
 * @returns Boolean
 */
export const visibilityHandler = (visibilityRules, formData) => {
  if (!visibilityRules) return true
  // 统一规则格式处理
  const normalizeRules = (rules) => {
    if (!rules) return []
    return Array.isArray(rules) ? rules : [rules]
  }
  // 递归评估规则集
  const evaluate = (ruleSet) => {
    const rules = normalizeRules(ruleSet.rules || ruleSet)
    const logic = ruleSet.logic || 'AND'
    const results = rules.map(rule => {
      if (rule.rules || rule.conditions) {
        return evaluate(rule) // 递归嵌套规则
      }
      return checkRule(rule, formData)
    })
    return logic === 'AND' 
      ? results.every(Boolean)
      : results.some(Boolean)
  }
  return evaluate(visibilityRules)
}